package com.jdk.demo.asynchronousFileChannel.读取数据;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Test1 {

	public static void main(String[] args) throws Exception {
		Path path = Paths.get("r.txt");
		AsynchronousFileChannel channel =  AsynchronousFileChannel.open(path, StandardOpenOption.READ);
		ByteBuffer buffer = ByteBuffer.allocate(3);
		// 从给定的文件位置开始，从该通道将字节序列读入给定的缓冲区
		channel.read(buffer, 0, "我是附加的参数", new CompletionHandler<Integer, String>() {
			@Override
			public void completed(Integer result, String attachment) {
				System.out.println("public void completed(Integer result, String attachment) result=" + result + " attachment=" + attachment);
				byte[] byteArray = buffer.array();
				for (int i = 0; i < byteArray.length; i++) {
					System.out.print((char)byteArray[i]);
				}
			}

			@Override
			public void failed(Throwable exc, String attachment) {
				System.out.println("public void failed(Throwable exc, String attachment) attachment" + attachment);
				System.out.println("getMessage=" + exc.getMessage());
			}
		});
		channel.close();
		Thread.sleep(2000);
	}

}
